#include "HeartbeatMonitor.h"

HeartbeatMonitor::HeartbeatMonitor(QObject *parent) :
   QObject(parent),
   theHeartbeatTimer(this),
   theResponseTimer(this),
   theHeartbeatIntervalSec(0),
   theResponseTimeoutSec(0)
{
   /// @todo get intervals from config manager

   connect(&theHeartbeatTimer, SIGNAL(timeout()),
           this, SLOT(slotHeartbeatRequest()));
   connect(&theResponseTimer, SIGNAL(timeout()),
           this, SLOT(slotRequestTimeout()));

   theHeartbeatTimer.start();
   theResponseTimer.setInterval(theResponseTimeoutSec);
   theResponseTimer.setSingleShot(true);
}

void HeartbeatMonitor::slotRegisterPlugin(Plugin *plugin)
{
   connect(this, SIGNAL(signalHearbeatRequest()),
           plugin, SLOT(slotHeatbeatRequest()));
   connect(plugin, SIGNAL(signalHeartbeatResponse()),
           this, SLOT(slotHeartbeatResponse()));

   theMonitoredPlugins.append(plugin);
}

void HeartbeatMonitor::slotHeartbeatRequest()
{
   theRespondedPlugins.clear();
   emit signalHearbeatRequest();
   theResponseTimer.start();
}

void HeartbeatMonitor::slotHeartbeatResponse()
{
   IPlugin *interface = qobject_cast<IPlugin*>(this->sender());
   Plugin *plugin = interface->getPlugin();
   theRespondedPlugins.append(plugin);
}

void HeartbeatMonitor::slotRequestTimeout()
{
   if(theMonitoredPlugins != theRespondedPlugins)
   {
      theHeartbeatTimer.stop();
      emit signalKillApplication();
   }
}
